package com.hefan.monitor.green;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20160621.ImageDetectionRequest;
import com.aliyuncs.green.model.v20160621.ImageDetectionResponse;
import com.aliyuncs.green.model.v20160621.ImageResultsRequest;
import com.aliyuncs.green.model.v20160621.ImageResultsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hefan.common.ons.ONSConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("checkYellowService")
public class CheckYellowService {
	private Logger logger = LoggerFactory.getLogger(CheckYellowService.class);
	
	/**
	 * 异步图片检测接口
	 * @Title: AsyncImageDetectionSample   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param imgUrls
	 * @return      
	 * @return: List<Map<String,String>>
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年11月10日 下午7:39:05
	 */
	public List<Map<String,String>> AsyncImageDetectionSample(List<String> imgUrls){
		List<Map<String,String>> resList = new ArrayList<Map<String,String>>();
        //请替换成你自己的accessKeyId、accessKeySecret
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ONSConstants.AccessKey, ONSConstants.SecretKey);
        IAcsClient client = new DefaultAcsClient(profile);
        ImageDetectionRequest imageDetectionRequest = new ImageDetectionRequest();
        /**
         * 设置成异步调用
         * true: 异步
         */
        imageDetectionRequest.setAsync(true);
        /**设置服务场景
         * 异步图片检测支持多个场景:
         * porn:  黄图检测
         * ocr:  ocr文字识别
         * illegal: 暴恐敏感检测
         */
        //场景请根据业务自需要设置，不一定要设置所有的场景
        imageDetectionRequest.setScenes(Arrays.asList("porn"));
        /**
         * 设置检测的图片链接
         * 异步图片检测一次支持最多50张图片进行检测,  请传递数组
         */
        imageDetectionRequest.setImageUrls(imgUrls);
        try {
            ImageDetectionResponse imageDetectionResponse = client.getAcsResponse(imageDetectionRequest);
            System.out.println(JSON.toJSONString(imageDetectionResponse));
            if("Success".equals(imageDetectionResponse.getCode())){
                List<ImageDetectionResponse.ImageResult> imageResults = imageDetectionResponse.getImageResults();
                if(imageResults != null && imageResults.size() > 0) {
                    for (ImageDetectionResponse.ImageResult imageResult : imageResults) {
                        String taskId = imageResult.getTaskId();
                        Map<String,String> map = new HashMap<String,String>();
                        map.put("taskId", taskId);
                        String imageName = imageResult.getImageName();
                        map.put("imageName", imageName);
                        resList.add(map);
                    }
                }
            	return resList;
            }else{
                logger.info("异步鉴黄上传失败："+JSON.toJSONString(imageDetectionResponse));
                return resList;
            }
        } catch (Exception e) {
            logger.error("异步鉴黄上传失败："+e.getMessage());
            return resList;
        }
	}
	
	public List<Map<String,String>> AsyncImageDetectionResultSample(List<String> taskIds){
		List<Map<String,String>> resList = new ArrayList<Map<String,String>>();
        //请替换成你自己的accessKeyId、accessKeySecret
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ONSConstants.AccessKey, ONSConstants.SecretKey);
        IAcsClient client = new DefaultAcsClient(profile);
        //批量异步图片检测结果获取, 最多支持100个taskId
        ImageResultsRequest imageResultsRequest = new ImageResultsRequest();
        imageResultsRequest.setTaskIds(taskIds);
        try {
            ImageResultsResponse imageResultsResponse = client.getAcsResponse(imageResultsRequest);
            if("Success".equals(imageResultsResponse.getCode())) {
                List<ImageResultsResponse.ImageDetectResult> imageDetectResults =  imageResultsResponse.getImageDetectResults();
                if(imageDetectResults != null && imageDetectResults.size() > 0) {
                    for (ImageResultsResponse.ImageDetectResult imageDetectResult : imageDetectResults) {
                        if("Success".equals(imageResultsResponse.getCode())
                                && "TaskProcessSuccess".equals(imageDetectResult.getStatus())) {
                            ImageResultsResponse.ImageDetectResult.ImageResult imageResult = imageDetectResult.getImageResult();
                            //porn场景对应的检测结果放在pornResult字段中
                            //ocr场景对应的检测结果放在ocrResult字段中
                            //illegal场景对应的检测结果放在illegalResult字段中
                            //请按需获取
                            /**
                             * 黄图检测结果
                             */
                            ImageResultsResponse.ImageDetectResult.ImageResult.PornResult pornResult = imageResult.getPornResult();
                            if (pornResult != null) {
                                /**
                                 * 绿网给出的建议值, 0表示正常，1表示色情，2表示需要review
                                 */
                                Integer label = pornResult.getLabel();
                                /**
                                 * 黄图分值,  0-100
                                 */
                                Float rate = pornResult.getRate();
                                // 根据业务情况来做处理
                                String taskId = imageResult.getTaskId();
                                Map<String,String> map = new HashMap<String,String>();
                                map.put("taskId", taskId);
                                String imageName = imageResult.getImageName();
                                map.put("imageName", imageName);
                                map.put("label", label.toString());
                                map.put("rate", rate.toString());
                                resList.add(map);
                            }
                        }
                    }
                    return resList;
                }
            }
            logger.info("异步鉴获取结果失败："+JSON.toJSONString(imageResultsResponse));
            return resList;
        } catch (Exception e) {
            logger.error("异步鉴黄获取结果失败："+e.getMessage());
            return resList;
        }
	}
	
	
	public static void main(String[] args) {
		CheckYellowService service = new CheckYellowService();
//		List<String> ls = new ArrayList<String>();
//		ls.add("http://liveapptestpic.oss-cn-hangzhou.aliyuncs.com/AppTest/7191564_7191564hefan20161109155000/1.jpg");
//		List<Map<String,String>> list = service.AsyncImageDetectionSample(ls);
//		System.out.println("长度"+list.size()+",号"+list.get(0).get("taskId"));
		//89496fe2-306e-419e-b4d2-ec98f2be3ceb-1479534040058
		List<String> ls = new ArrayList<String>();
		ls.add("89496fe2-306e-419e-b4d2-ec98f2be3ceb-1479534040058");
		List<Map<String,String>> list = service.AsyncImageDetectionResultSample(ls);
		System.out.println("长度"+list.size()+",号"+list.get(0).toString());
	}

}
